# coding:utf-8
# __author__ = 'ChenHongyan'

import allure

from common.logger import logger
# from common.mysql_operate_order import db
from common.mysql_operate_order import db
from common.read_data import rd
from api.apikey import ak


@allure.step("返回结果")
def step_1(result):
    logger.info("返回结果：{}".format(result))



@allure.step("数据解析")
def user_order_delivery(method,base_url,url,headers,params,json,json_data):
    if "true" or "false" in json_data:
        # 将json入参中value是false，true的转换成布尔值False，True
        json_data=json_data.replace("true", "True").replace("false", "False")
    else:
        raise
    try:
        logger.info("*************** 开始执行用例 ***************")
        if '/{}' in url:
            data_dict = {
                    'url': base_url + url.format(rd.read_extract_yaml('checkout_id')),
                    'headers': eval(headers),
                    'params': eval(params),
                    json: eval(json_data)
                }
        elif 'goodsorderid' in url:
            data_dict = {
                'url': base_url + url.format(rd.read_extract_yaml('goodsorderid')),
                'headers': eval(headers),
                'params': eval(params),
                json: eval(json_data)
            }
        else:
            data_dict = {
                'url': base_url + url,
                'headers': eval(headers),
                'params': eval(params),
                json: eval(json_data)
            }
        logger.info("执行接口请求{}".format(data_dict))
        # 反射+解包
        res = getattr(ak, method)(**data_dict)
        step_1(res.text)
        # logger.info("返回结果{}".format(res.text))
        return res
    except Exception as e:
        logger.info("test_01的报错信息：{}".format(e))
        raise

@allure.step("抽取接口返回值数据")
def get_extract_data(extract,expr,res):
    if extract is not None:
        extract = extract.split(';')
        expr = expr.split(';')
        for i in range(len(extract)):
            newValue = rd.get_text(res, expr[i])
            rd.write_extract_yaml({str(extract[i]): str(newValue)})
            if str(extract[i]) == "url":
                rd.update_yaml_value("url",str(newValue))
                rd.update_yaml_value('tenant_id', str(newValue)[54:72])
                logger.info("tenant_id是：{}，提取的value是：{}".format(extract[i], str(newValue)[54:72]))
                rd.update_yaml_value('goodsorderid',str(newValue)[103:123])
                logger.info("goodsorderid：{}，提取的value是：{}".format(extract[i], str(newValue)[103:123]))
                rd.update_yaml_value('tiens_code', str(newValue)[145:317])
                logger.info("tiens_code：{}，提取的value是：{}".format(extract[i], str(newValue)[145:317]))

@allure.step("断言")
def assert_validate(excel,sheet,r,res,expr,exp_msg,path):
    try:
        rel_result = rd.get_text(res, expr)
        if str(rel_result) == str(exp_msg):
            sheet.cell(r,11).value = '通过'
            logger.info('测试用例执行成功')
        else:
            print("提取真实结果字符类型：",type(rel_result))
            print("预期结果字符类型：",type(exp_msg))
            sheet.cell(r, 11).value = '失败'
            logger.info('测试用例执行失败')
    except Exception as e:
        sheet.cell(r, 11).value = '返回结果错误，或者表达式data[8]错误'
        logger.info("返回结果错误，或者表达式data[8]错误，{}".format(e))
        raise
    finally:
        excel.save(path)

@allure.step("数据库校验")
def check_user_order(sheet,excel,path,r,sql,goodsid):
     if sql is not None:
         sql=sql.format(rd.read_extract_yaml(goodsid))
         rep = db.select_db(sql)
         for dis in rep:
             if dis['user_distributor_id'] == rd.read_extract_yaml('joyocode'):
                 sheet.cell(r, 23).value = '数据库校验通过'
                 logger.info("数据库校验通过")
             else:
                 sheet.cell(r, 23).value = '数据库校验失败'
                 logger.info("数据库校验失败")
     excel.save(path)
     logger.info("*************** 结束执行用例 ***************")

